import echarts from '@/utils/echarts'
import { unref } from 'vue'
import { useResizeObserver, useThrottleFn, tryOnUnmounted } from '@vueuse/core'

/**
 * @param refEl dom 元素
 * <div ref='chart'></div>
 * import { useEcharts } from '@/hooks/useEcharts'
 * const elChart = ref<any>(null)
 * const chart = useEcharts(elChart1)
 * const options = {...}
 * chart.setOptions(options)
*/
export const useEcharts = (refEl:any) => {
  let chartInstance:any = null
  // 初始化实例
  const initChart = (options:any, config?: boolean) => {
    // const el = unref(refEl)
    const el = refEl.value
    const isdom = el instanceof HTMLElement
    if (!el && !isdom) {
      throw new Error('无效的dom对象！')
    }
    chartInstance = echarts.init(el)
    chartInstance.setOption(options, config)
    // 监听容器变化
    useResizeObserver(
      unref(refEl),
      useThrottleFn(resize, 200)
    )
  }

  const resize = () => {
    chartInstance?.resize()
  }
  const clear = () => {
    chartInstance?.clear()
  }

  // 注销echatrs实例
  tryOnUnmounted(() => {
    if (!chartInstance) return
    chartInstance.dispose()
    chartInstance = null
  })

  return {
    chartInstance,
    clear,
    initChart
  }
}
